package cc.android.testapp;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import cc.android.testapp.util.CLog;
import cc.android.testapp.cfg.Config;
import cc.android.testapp.cfg.ConfigHelper;
import cc.android.testapp.xp.hooker.adblock.util.ADBCfg;
import cc.commons.util.FileUtil;

public class TAContentProvider extends ContentProvider {

    private static final HashMap<String, TAReslove> mResolves = new HashMap<>();

    /**
     * 注册请求解析器
     *
     * @param pType    解析的类型,必须以'/'开头
     * @param pResolve 解析器
     * @return 被替换的解析器
     */
    public static TAReslove registerReslove(String pType, TAReslove pResolve) {
        return mResolves.put(pType, pResolve);
    }

    @Override
    public String getType(Uri uri) {
        if (uri.getPath() == null) return null;

        String tType = uri.getPath();
        TAReslove tResolve = mResolves.get(tType);
        if (tResolve != null) {
            return tResolve.handleRequest(uri.getQueryParameter("pn"), tType, uri);
        }
        return null;
    }


    @Override
    public boolean onCreate() {
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String
            selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[]
            selectionArgs) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String
            selection, @Nullable String[] selectionArgs) {
        return 0;
    }

    public static interface TAReslove {

        /**
         * 处理来自客户端的请求
         *
         * @param pPName 包名
         * @param pType  处理类型
         * @param pUri   原始URI
         * @return 需要返回的值, 注意处理成功必须返回非null值, 否则会被重复执行
         */
        String handleRequest(String pPName, String pType, Uri pUri);
    }
}
